// import './iconify'
// import './iconfont'
import FastCrud, { useTypes } from '@fast-crud/fast-crud'
import { FsExtendsEditor, FsExtendsUploader } from '@fast-crud/fast-extends'
import '@fast-crud/fast-extends/dist/style.css'
import '@fast-crud/fast-crud/dist/style.css'
// import permission from "./permission";
import type { App } from 'vue'
import { shallowRef } from 'vue'
import CustomLayout from '@/layout/custom-layout.vue'
import ui from '@fast-crud/ui-element'
import dayjs from 'dayjs'
import { setLocal, getLocal } from '@/lib/utils'
function install(app: App) {
  app.use(ui)
  const options: any = {
    logger: { off: { tableColumns: false } },
    // 此处配置公共的dictRequest（字典请求）
    // async dictRequest({ dict }) {
    //   const url = String(dict?.url)
    //   return await $http.get(url)
    // },
    //公共crud配置
    commonOptions() {
      const getLocalPageSize = getLocal('pageSize') || 20
      const pageSize = Number(getLocalPageSize) > 50 ? 50 : Number(getLocalPageSize)
      return {
        container: {
          is: shallowRef(CustomLayout), //'fs-layout-card', // shallowRef(CustomLayout), //可以将自定义布局组件全局注册
        },
        table: {
          size: 'default',
          pagination: false,
          conditionalRender: {
            match(scope: any) {
              //不能用 !scope.value ， 否则switch组件设置为关之后就消失了
              const { value, key } = scope
              return !value && key != '_index' && value != false
            },
            render(scope: any) {
              return '-'
            },
          },
          remove: {
            confirmProps: {
              lockScroll: false,
            },
          },
        },
        request: {
          transformQuery: ({ page, form }: any) => {
            return { page: page.currentPage, size: page.pageSize, ...form }
          },
          transformRes: ({ res }: any) => {
            const data = res.data
            return { currentPage: Number(data.page), pageSize: Number(data.size), ...data }
          },
        },
        form: {
          async afterSubmit({ mode }: any) {
            if (mode === 'add') {
              ElNotification.success({ message: '添加成功' })
            } else if (mode === 'edit') {
              ElNotification.success({ message: '保存成功' })
            }
          },
          col: {
            span: 24,
          },
          display: 'flex', //表单布局
          wrapper: {
            width: '900px',
            // saveRemind: true,
            // saveRemind: () => {}, // 关闭保存提示
            'lock-scroll': false,
          },
        },
        addForm: {
          wrapper: {
            title: '新增',
          },
        },
        actionbar: {
          buttons: {
            add: {
              text: '新增',
              icon: 'ion:add-outline',
            },
          },
        },
        columns: {
          createdDate: {
            title: '创建时间',
            type: 'text',
            search: {
              show: true,
              component: {
                name: 'el-date-picker',
                props: {
                  type: 'datetimerange',
                },
                clearable: true,
              },
              col: {
                span: 8,
              },
              order: 1000,
            },
            column: {
              width: 180,
              order: 1000,
              resizable: true,
              formatter({ value }: { value: string | Date | number }) {
                return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
              },
            },
            form: {
              show: false,
            },
          },
        },
        rowHandle: {
          buttons: {
            view: { text: null, icon: 'ion:eye-outline', size: 'default' },
            // copy: { show: true, text: null, icon: 'ion:copy-outline', size: 'default' },
            edit: { text: null, icon: 'ion:create-outline', size: 'default' },
            remove: { type: 'danger', text: null, icon: 'ion:trash-outline', size: 'default' },
          },
          dropdown: {
            more: {
              size: 'default',
            },
          },
        },
        pagination: {
          'default-page-size': pageSize,
          pageSize: pageSize,
          onChange: (currentPage: number, pageSize: number) => {
            setLocal('pageSize', pageSize)
          },
        },
      }
    },
  }
  app.use(FastCrud, options)
  // const { addTypes } = useTypes()
  // addTypes({
  //   // 自定义类型，字段类型，fs会根据字段类型，生成出一些默认配置
  //   notForm: {
  //     addForm: { show: false }, // 不在新增表单中展示
  //     editForm: { show: false }, // 不在编辑表单中展示
  //   },
  // })
  //文件上传
  const token = getLocal('token')
  app.use(FsExtendsUploader, {
    defaultType: 'form',
    // 上传实现的配置，你使用哪一个就配置哪一个即可
    form: {
      action: '/api/file-sys/upload',
      name: 'file',
      headers: { Authorization: `Bearer ${token}` },
      // async uploadRequest({ file, action }) {
      //   自定义文件上传请求
      //   return await axios.request();
      // }
    },
  })
  //富文本编辑器
  type InsertFnType = (url: string, alt?: string, href?: string) => void
  const editorConfig: any = {
    //富文本编辑器的公共配置
    wangEditor5: {
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            fieldName: 'file',
            server: '/api/file-sys/upload',
            headers: {
              Authorization: `Bearer ${token}`,
            },
            customInsert(res: any, insertFn: InsertFnType) {
              let domain = import.meta.env.VITE_APP_BASE_API
              if (import.meta.env.PROD) {
                domain = '/'
              }
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(`${domain}${res.data.url}`)
            },
          },
        },
      },
      // toolbarConfig: {
      //   toolbarKeys: [],
      // },
    },
  }
  app.use(FsExtendsEditor, editorConfig)
  // app.use(permission);
}

export default {
  install,
}
